package com.hlkj.pay.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.pay.app.merchant.ext.impl.easypay.utils.EasyPayBase64;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 微信OAuth2.0授权
 * 静默回去用户appid
 */
public class AlipayOAuthUtils {

    public static String getAuthCode(String pubAppid, String redirectUrl) {
        Map<String, String> params = new HashMap<>();
        params.put("app_id", pubAppid);
        params.put("redirect_uri", redirectUrl);
        params.put("response_type", "code");
        params.put("scope", "auth_base");
        params.put("state", "123456");
        return "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?" + mapToQuery(params);
    }

    private static String mapToQuery(Map<String, String> params) {
        StringBuilder queryString = new StringBuilder();
        Set<Map.Entry<String, String>> entrySet = params.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue();
            // URL 编码
            String encodedKey = URLEncoder.encode(key);
            String encodedValue = URLEncoder.encode(value);
            if (queryString.length() > 0) {
                queryString.append("&");
            }
            queryString.append(encodedKey).append("=").append(encodedValue);
        }
        return queryString.toString();
    }

    public static CommonResult<String> getToken(String pubAppid, String rsaPrivateKey, String authCode) throws Exception {
        try {

            Map<String, String> accessMap = new HashMap<>();
            accessMap.put("app_id", pubAppid);
            accessMap.put("method", "alipay.system.oauth.token");
            accessMap.put("format", "JSON");
            accessMap.put("charset", "utf-8");
            accessMap.put("sign_type", "RSA2");
            accessMap.put("timestamp", DateUtils.getDateString(DatePattern.NORM_DATETIME_PATTERN));
            accessMap.put("version", "1.0");
            accessMap.put("grant_type", "authorization_code");
            accessMap.put("code", authCode);
            accessMap.put("sign", sign(accessMap, rsaPrivateKey));
            String accessRes = requestGet("https://openapi.alipay.com/gateway.do", accessMap);
            JSONObject accessObj = JSONUtil.parseObj(accessRes);
            if (accessObj.containsKey("errcode")) {
                return CommonResult.error(1, "获取授权失败错误码 " + accessObj.containsKey("errcode"));
            }
            return CommonResult.success(accessObj.getStr("openid"));
        } catch (Exception e) {
            return CommonResult.error(1, e.getMessage());
        }
    }

    private static String sign(Map<String, String> accessMap, String rsaPrivateKey) throws Exception {
        com.alibaba.fastjson.JSONObject dataJson = (com.alibaba.fastjson.JSONObject) JSON.toJSON(accessMap);
        String signContent = JSON.toJSONString(dataJson, SerializerFeature.MapSortField);
        try {
            byte[] keyBytes = EasyPayBase64.decode2Byte(rsaPrivateKey);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyFactory.generatePrivate(spec);

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(priKey);
            signature.update(signContent.getBytes(StandardCharsets.UTF_8));
            return EasyPayBase64.encode2String(signature.sign());
        } catch (Exception e) {
            //签名失败
            throw new Exception("签名异常: " + e.getMessage());
        }
    }

    @SuppressWarnings("deprecation")
    private static String requestGet(String urlPath, Map<String, String> params) throws Exception {
        HttpURLConnection connection = null;
        try {
            StringBuilder queryString = new StringBuilder();
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                String key = entry.getKey();
                String value = entry.getValue();
                // URL 编码
                String encodedKey = URLEncoder.encode(key);
                String encodedValue = URLEncoder.encode(value);
                if (queryString.length() > 0) {
                    queryString.append("&");
                }
                queryString.append(encodedKey).append("=").append(encodedValue);
            }

            // 创建URL对象，传入你想请求的URL
            URL url = new URL(urlPath + "?" + queryString.toString());
            System.out.println(urlPath + "?" + queryString);
            // 打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式为GET
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            // 设置请求超时
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 获取响应码
            int responseCode = connection.getResponseCode();
            // 如果响应码是200（成功），读取响应内容
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 创建BufferedReader来读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
                String inputLine;
                StringBuilder response = new StringBuilder();
                // 按行读取响应内容
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // 输出响应内容
                return response.toString();
            } else {
                throw new Exception("授权请求异常，" + responseCode);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            if (connection != null) connection.disconnect();
        }
    }

    public static void main(String[] args) {
        String pubAppid = "13123123132";
        String secretKey = "fsfsddssd";

        String redirectUrl = "https://test-api.hbhlpay.com/applyments.ffpay/test";
        try {
            String openId = AlipayOAuthUtils.getAuthCode(pubAppid, redirectUrl);
            System.out.println(openId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
